package org.easy.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.easy.common.domain.BzConsumerDO;
import org.easy.module.mapper.BzConsumerMapper;
import org.easy.module.service.BzConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName: BzConsumerServiceImpl
 * @Description: 客户信息Service实现类
 * @Author zhouzhixin
 * @Date 2021/11/26
 * @Version 1.0
 */
@Service
public class BzConsumerServiceImpl extends ServiceImpl<BzConsumerMapper, BzConsumerDO> implements BzConsumerService {

    BzConsumerMapper bzConsumerMapper;

    @Autowired
    public void init(BzConsumerMapper bzConsumerMapper) {
        this.bzConsumerMapper = bzConsumerMapper;
    }

    @Override
    public List<BzConsumerDO> getAllConsumerTest() throws InterruptedException {
        CopyOnWriteArrayList<BzConsumerDO> consumerList = new CopyOnWriteArrayList<>();
        int baseThreadNum = 5;
        long keepAliveTime = 5L;
        int consumerCount = bzConsumerMapper.selectCount(new QueryWrapper<>());
        int num = (int) Math.ceil(consumerCount / 1000.0);
        CountDownLatch countDownLatch = new CountDownLatch(num);

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(baseThreadNum, num,
                keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<>(baseThreadNum),
                new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i < num; i++) {
            int finalNum = i;
            threadPoolExecutor.execute(() -> {
                long pageSize = 1000;
                System.out.println(Thread.currentThread().getName() + ":" + finalNum);
                long pageNo = finalNum * pageSize;
                // Page<BzConsumerDO> page = new Page<>(pageNo, pageSize);
                System.out.println(Thread.currentThread().getName() + " pageNo:" + finalNum * pageSize + " pageSize:" + pageSize);
                List<BzConsumerDO> consumerDOList = bzConsumerMapper.getConsumerByPage(pageNo, pageSize);
                // List<BzConsumerDO> consumerDOList = bzConsumerMapper.selectPage(page, new QueryWrapper<BzConsumerDO>()).getRecords();
                if (CollectionUtils.isNotEmpty(consumerDOList)) {
                    consumerList.addAll(consumerDOList);
                    System.out.println(Thread.currentThread().getName() + ":" + consumerDOList.size());
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        threadPoolExecutor.shutdown();
        System.out.println(Thread.currentThread().getName() + ":" + consumerList.size());
        return consumerList;
    }
}
